package com.ray.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiSnsGetuserinfoBycodeRequest;
import com.dingtalk.api.request.OapiUserGetRequest;
import com.dingtalk.api.request.OapiUserGetUseridByUnionidRequest;
import com.dingtalk.api.response.OapiSnsGetuserinfoBycodeResponse;
import com.dingtalk.api.response.OapiUserGetResponse;
import com.dingtalk.api.response.OapiUserGetUseridByUnionidResponse;
import com.jfinal.core.Controller;
import com.ray.util.AccessTokenUtil;
import com.taobao.api.ApiException;

public class DingLoginController extends Controller {
	public void index() throws ApiException{ 
		DefaultDingTalkClient  client = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
		OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest();
		req.setTmpAuthCode(getPara("code"));
		OapiSnsGetuserinfoBycodeResponse response = client.execute(req,"dingoamdn80bczgvspo9wk","tyM_rAAxXBtLFwakm45Y7w_txPKKVSoQn55fog2zZVGXMMiFAdP0JsFV3_cqsT_E");
		String dingtoken = AccessTokenUtil.getToken();
		//获取UserId
		DingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getUseridByUnionid");                 
		OapiUserGetUseridByUnionidRequest request2 = new OapiUserGetUseridByUnionidRequest();
		request2.setUnionid(response.getUserInfo().getUnionid());
		request2.setHttpMethod("GET");
		OapiUserGetUseridByUnionidResponse userInfo = client2.execute(request2, dingtoken);
		
		if(0==userInfo.getErrcode()){
			//获取用户详情
			DingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get");
			OapiUserGetRequest request = new OapiUserGetRequest();
			request.setUserid(userInfo.getUserid());
			request.setHttpMethod("GET");
			OapiUserGetResponse response3 = client3.execute(request, dingtoken);
			UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUserid(), userInfo.getUserid());
			Subject subject = SecurityUtils.getSubject();
			subject.login(token);
			subject.getSession().setAttribute("user", response3);
			redirect("/");
		}else{
			redirect("/loginInit?code=1&icon=5");
		}
	}
}
